<?php
class Admin_AdminItemController extends Zend_Controller_Action
{
	public function init()
	{
		
	}
	public function preDispatch()
	{}
	public function indexAction()
	{
	if($this->getRequest()->isXmlHttpRequest()){
        $page = 	$this->getRequest()->getPost('page'); 
        $sidx = 	$this->getRequest()->getPost('sidx'); 
        $sord = 	$this->getRequest()->getPost('sord');

		$oper=			$this->getRequest()->getPost('oper'); 
		$id=				$this->getRequest()->getPost('id'); 
		$author=		$this->getRequest()->getPost('author');
		$category=	$this->getRequest()->getPost('category');
		$date=			$this->getRequest()->getPost('date');
		$link=			$this->getRequest()->getPost('link');
		$title=			$this->getRequest()->getPost('title');
		$visibility=$this->getRequest()->getPost('visibility');
		$search=		$this->getRequest()->getPost('_search');

		$articles=new Myblog_Model_Articles;
		$data=$articles->getArticles();
		$limit=100;
		
		
			if(!empty($oper) && !empty($id))
			{
			if($oper=='del'){
			
				if(strpbrk($id,','))
				{
					$ida=explode(',',$id);
					foreach($ida as $ids)
					{
					$q=Doctrine_Query::create()
					->from('Myblog_Model_Articles a')
					->delete()
					->where('a.article_id=?',$ids)
					->execute();
					}
				}else{
			$q=Doctrine_Query::create()
				->from('Myblog_Model_Articles a')
				->delete()
				->where('a.article_id=?',$id)
				->execute();
				$this->createFulltextIndexAction();
				}
			}
			if($oper=='edit' && isset($id) && isset($author) && isset($category) && isset($date) && isset($link) && isset($title) && isset($visibility) && isset($page))
			{
				$filter=new Zend_Filter_StripTags();
				$title=$filter->filter($title);
				$update=array('article_id'=>$id,'author'=>$author,'category_name'=>$category,'created_dt'=>$date,
							'link'=>$link,'title'=>$title,'visibility'=>$visibility,'page'=>$page);
				$q=Doctrine_Query::create()
					->update('Myblog_Model_Articles a')
					->set($update)
					->where('a.article_id=?',$id)
					->execute();
					
			}
			$this->createFulltextIndexAction();
		}
		
		$count=Doctrine::getTable('Myblog_Model_Articles')
			->count();

		  if ($count > 0)
        	{
            $totalPages = ceil($count / $limit);
      	    }else
        		{
            	$totalPages = 0;
        		}

		 if ($page > $totalPages)
         {
          $page = $totalPages;
      	 }

		 $offset = $limit * $page - $limit;
       	 if ($offset < 0)
       	 {
            $offset = 0;
       	 }
      	
       	
		for($i=0;$i<$count;$i++) {

		$responce->rows[$i]['id']=$data[$i]["ID"];
		$responce->rows[$i]['cell']=array($data[$i]["ID"],$data[$i]["title"],$data[$i]["category"],$data[$i]["author"],$data[$i]["link"],$data[$i]["page"],$data[$i]["created"],$data[$i]['visibility'],'',$data[$i]["comments"]);
		}
		$response = array('page' => $page, 'total' => $totalPages, 'records' => $count, 'rows' => $responce->rows);
        $this->_helper->json($response);

		} 
	}

			
	public function displayAction()
	{
		if($this->getRequest()->isGet())
		{
		$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
		$validators=array('id'=>array('NotEmpty','Int'));
		$url=$this->getRequest()->getRequestUri();
		$input=new Zend_Filter_Input($filters,$validators);
		$input->setData($this->getRequest()->getParams());
		if($input->isValid()){
		$q=Doctrine_Query::create()
			->from('Myblog_Model_Articles')
			->where('article_id=?',$input->id);
		if(!empty($q)){
		$result=$q->fetchArray();
		$this->view->headTitle('Статьи');
		$this->view->item=$result[0];
				}else{
						throw new Zend_Action_Exception('Page not found',404);
					 }
				}
			}
		}

		public function createAction()
		{
			$form=new Myblog_Form_ItemCreate();
			$this->view->form=$form;
				if($this->getRequest()->isPost())
					{
					if($form->isValid($this->getRequest()->getPost())){
						$item=new Myblog_Model_Articles;
						$item->fromArray($form->getValues());
					
						$item->save();
						$q=Doctrine_Query::create()
							->from('Myblog_Model_Articles a')
							->select('a.article_id')
							->where('a.created_dt=?',$date)
							->fetchArray();	
						$item->link='/catalog/item/display/'.$q[0]['article_id'];
						$item->save();
							
					$this->createFulltextIndexAction();
						
						$this->_helper->getHelper('FlashMessenger')
							->addMessage('Новая статья добавлена!');
						$this->_redirect('/admin/catalog/item/success');
						
						
			}
		}
	}

	public function deleteAction()
	{
		$filters=array('ids'=>array('HtmlEntities','StripTags','StringTrim'));
		$validators=array('ids'=>array('NotEmpty','Int'));
		$input=new Zend_Filter_Input($filters,$validators);
		$input->setData($this->getRequest()->getParams());
		if($input->isValid()){
			if(!empty($input->ids)){
			$q=Doctrine_Query::create()
				->delete('Myblog_Model_Articles a')
				->whereIn('a.article_id',$input->ids);
		$result=$q->execute();
		
		$this->createFulltextIndexAction();
		
		$this->_helper->getHelper('FlashMessenger')
			->addMessage('Статья успешно удалена!');
		$this->_redirect('/admin/catalog/item/success');
		}else{
				$this->_helper->getHelper('FlashMessenger')
					->addMessage('Не выбраны статьи для удаления');
				$this->_redirect('/admin/catalog/item/success');
			 }	
		
	  }else{
			throw new Zend_Controller_Action_Exception('Invalid input');
			}	
	}
	
	
	public function updateAction()
	{
	$form=new Myblog_Form_ItemUpdate;
	$this->view->form=$form;

	if($this->getRequest()->isXmlHttpRequest())
	{
	$this->_helper->getHelper('layout')->disableLayout();
	$selectCat = $this->getRequest()->getPost('selectcat');
	
		if(!empty($selectCat) && $selectCat !=='')
		{
		$q=Doctrine_Query::create()
			->from('Myblog_Model_Articles a')
			->select('a.category_name')
			->fetchArray();
			if(!empty($q))
			{
			$select = array('select'=>$q[0]['category_name']);
			$this->_helper->json($select);	
			}
		
		}
	}

	if($this->getRequest()->isPost() && $form->isValid($this->_getAllParams())){
	$data=$this->getRequest()->getPost();
		if(!empty($data)){
		$q=Doctrine::getTable('Myblog_Model_Articles')
				->find($data['article_id']);
		$q->fromArray($data);
		}
		else{
			throw new Zend_Controller_Action_Exception('Invalid input');
			}
	$q->save();
	$this->_helper->getHelper('FlashMessenger')
		->addMessage('Статья успешно обновлена');
	$this->_redirect('/admin/catalog/item/success');
	}
	else{
$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
$validators=array('id'=>array('NotEmpty','Int'));
$input=new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());

		if($input->isValid()){
		$q=Doctrine_Query::create()
			->from('Myblog_Model_Articles a')
			->where('article_id=?',$input->id);
		$result=$q->fetchArray();
		
			if(count($result)==1){
			
			$this->view->form->populate($result[0]);
			$this->view->item=$result[0];	
			}			
		}
	}
}	
	public function createFulltextIndexAction()
	{
    exit;//not working
	$this->_helper->getHelper('layout')->disableLayout();
	$q=Doctrine_Query::create()
		->from('Myblog_Model_Articles a')
		->where('a.visibility=?','yes');
	$result=$q->fetchArray();
        $cont = new Zend_Registry();
        $cont->set('askar',array('askar'=>'ok'));
        var_dump($cont);exit;
	Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
	$config=$this->getInvokeArg('bootstrap')->getOption('indexes');
	$index=Zend_Search_Lucene::create($config['indexPath']);
		foreach($result as $r){
		$doc=new Zend_Search_Lucene_Document();
		$doc->addField(Zend_Search_Lucene_Field::Text('article',$r['article'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('title',$r['title'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('author',$r['author'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('category_name',$r['category_name'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('article_id',$r['article_id'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('link',$r['link'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('description',$r['description'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('created_dt',$r['created_dt'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('img',$r['img'],'UTF-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('visibility',$r['visibility'],'UTF-8'));
		$index->addDocument($doc);
		}

		//$count=$index->count();
		//	$this->_helper->getHelper('FlashMessenger')
		//		->addMessage('Проиндексированы '.$count.' документов.');
		//	$this->_redirect('/admin/catalog/item/success');
	}	

	public function successAction()
	{
		if($this->_helper->getHelper('FlashMessenger')->getMessages()){
			$this->view->messages=$this->_helper
				->getHelper('FlashMessenger')->getMessages();
				header("Refresh:3;/admin/index");
			
			}else{
					$this->_redirect('/admin/index');
				 }
		}

}

